#include "mpx_supt.h"
#include <stdio.h>
#include <dir.h>

#define MAX_PATH_SIZE 50
#define ERR_DIR_OPEN  10
#define ERR_NO_FILE 20


#define SUCCESS 0


int main ( )
{
	char namebuf[60];
	long *filesize;
	/*sys_open_dir ("d:\\tc3\\turboc3\\mpx");   */
	sys_open_dir (NULL);

	sys_get_entry ( namebuf, 60, filesize);
	sys_close_dir();
	return (SUCCESS);
}

/* static char array to store the current directory */
static char curr_path[MAX_PATH_SIZE];

/* Entry of ffblk  */
static struct ffblk file_block;

/* */
static int num_entries;


/* open a directory, retrun zero if successful, otherwise return non-zero integers to represent various errors. */

int sys_open_dir ( char dir_name[] )
{
	int res;
	char temp_path[MAX_PATH_SIZE];
	char file_type1[]="\\*.*";
	char file_type2[]="*.*";
	/* for conuity, have to think of whether the directory is already opened. */
	if ( curr_path[0]!= '\0') /* The directory is already open */
	return (ERR_DIR_OPEN);


	temp_path[0]='\0';
	/* Analyze the dir_name,which is either NULL, or some path. */

	if (dir_name!=NULL) /* No parameter, just open current directory */
	{
		strcpy(temp_path,dir_name);

		strcat(curr_path, temp_path);
		printf("Current directory is %s\n",temp_path);

		/* check whether there are some files there,otherwise return error code-ERR_NO_FILE  */
		strcat(curr_path,file_type1);
	}
	else
	{
		strcat(curr_path,file_type2);
	}
	printf("Current search files are %s\n",curr_path);
	res = findfirst(curr_path,&file_block,0);
	printf("%d\n",res);

	if (!res)
	{
		num_entries = 0;

		return (SUCCESS);

	}
	/* Set the curr_path*/
	else
	{
		printf("Can't locat files!\n");
		return ( ERR_NO_FILE);
	}
}

/* sys_get_entry: get a directory entry */
/* RETURNS: integer error code, zero if success.*/
int sys_get_entry (char name_buf[], /* file name buffer */
			int  buf_size, /* name buffer size */
			long *file_size_p /* file size variable */
			)
{
	int ent;

	ent = findfirst ( curr_path, &file_block, 0);
	num_entries ++;

	while (!ent)
	{
		strcpy(name_buf, file_block.ff_name);
		*file_size_p = file_block.ff_fsize;
		printf ("%40s\t", name_buf);
		printf ("%10ld\n", *file_size_p);
		ent = findnext (&file_block);
		num_entries++;
	}

	printf ("Totally %d files have been found.", num_entries);
	return (SUCCESS);
}


/* sys_close_dir: close a directory */
/* RETURNS: integer error code, zero if OK */

int sys_close_dir (void)
{
	curr_path[0]='\0';
	return (0);
}
